﻿using Dapper;
using SenGe.Domain;
using System.Data;

namespace SenGe.Infrastructure
{
    /// <summary>
    /// 用户相关仓储服务
    /// </summary>
    public class SenUserRepository : BaseRepository<SenUser>, ISenUserRepository
    {
        /// <summary>
        /// 数据库连接对象
        /// </summary>
        private readonly IDbConnection _db;
        /// <summary>
        /// 构造函数传入依赖注入对象
        /// </summary>
        /// <param name="db">db</param>
        public SenUserRepository(IDbConnection db) : base(db)
        {
            _db = db;
        }

        /// <summary>
        /// 检查注册信息
        /// </summary>
        /// <returns></returns>
        public async Task<UserRegisterCheckResult> CheckRegisterInfo(UserRegisterModel model)
        {
            var sql = @"SELECT * FROM sen_user WHERE `Name` = @Name AND Id != @Id AND IsDeleted = 0 LIMIT 0,1;";
            SenUser? dbItem = await _db.QueryFirstOrDefaultAsync<SenUser>(sql, model);
            if (dbItem != null) return UserRegisterCheckResult.NameExists;
            sql = @"SELECT * FROM sen_user WHERE UserName = @UserName AND Id != @Id AND IsDeleted = 0 LIMIT 0,1;";
            dbItem = await _db.QueryFirstOrDefaultAsync<SenUser>(sql, model);
            if (dbItem != null) return UserRegisterCheckResult.UserNameExists;
            if (!string.IsNullOrEmpty(model.Phone))
            {
                sql = @"SELECT * FROM sen_user WHERE Phone = @Phone AND Id != @Id AND IsDeleted = 0 LIMIT 0,1;";
                dbItem = await _db.QueryFirstOrDefaultAsync<SenUser>(sql, model);
                if (dbItem != null) return UserRegisterCheckResult.PhoneExists;
            }
            return UserRegisterCheckResult.Success;
        }
        /// <summary>
        /// 通过登录用户名获取用户Dto
        /// </summary>
        /// <param name="userName">登录用户名</param>
        /// <returns></returns>
        public async Task<DtoSenUser?> GetUserByUserName(string userName)
        {
            return await _db.QueryFirstOrDefaultAsync<DtoSenUser>("SELECT Id,`NAME`,UserName,`Password`,Avatar FROM sen_user WHERE UserName = @UserName;", new { UserName = userName });
        }
        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="user">用户模型</param>
        /// <returns></returns>
        public async Task<bool> ChangePassWord(DtoSenUser user)
        {
            var sql = @"UPDATE sen_user SET `Password` = @PassWord WHERE Id = @Id;";
            return await _db.ExecuteAsync(sql, user) > 0;
        }
        /// <summary>
        /// 更新最新登录时间
        /// </summary>
        /// <param name="user">用户模型</param>
        /// <returns></returns>
        public async Task<bool> UpdateLastLoginTime(DtoSenUser user)
        {
            var sql = @"UPDATE sen_user SET LastLoginTime = NOW() WHERE Id = @Id;";
            return await _db.ExecuteAsync(sql, user) > 0;
        }
    }
}
